<template>
   <el-form   ref="ruleFormRef" v-loading="loading" :inline="true" :rules="rules" :model="form" label-width="140px">
    <el-form-item label="当前订单状态:" prop="orderStatus" >
      <el-select disabled  v-model="form.orderStatus" placeholder="请选择订单状态">
        <el-option v-for="item in orderstatus" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
      </el-select>
    </el-form-item>

    <div v-if="showNextStatus">
      <el-form-item label="下一步订单状态:" prop="nextorderStatus">
      <el-select disabled  v-model="form.nextorderStatus" placeholder="请选择订单状态">
        <el-option v-for="item in orderstatus" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
      </el-select>
    </el-form-item>
    </div>
    
    
    <div v-if="form.orderStatus === '订金订单'">
      <el-form-item label="定金金额:" prop="reserveAmount">
      <el-input v-model="form.reserveAmount" />
    </el-form-item>
    <el-form-item label="预估金额:" prop="estimatedAmount">
      <el-input v-model="form.estimatedAmount" />
    </el-form-item>
    <el-form-item label="执行人:" prop="executor">
      <el-tree-select v-model="form.executor" :data="data" :render-after-expand="false" placeholder="请选择设计主管" />
    </el-form-item>
    </div>

    <div v-else-if="form.orderStatus === '派单量尺'">
    <el-form-item label="执行人:" prop="executor">
      <el-tree-select v-model="form.executor" :data="data" :render-after-expand="false" placeholder="请选择设计师" />
    </el-form-item>
    </div>
    <div v-else-if="form.orderStatus === '合同确图'">
    <el-form-item label="执行人:" prop="executor">
      <el-tree-select v-model="form.executor" :data="data" :render-after-expand="false" placeholder="请选择订单管理员" />
    </el-form-item>
    </div>
    <div v-else-if="form.orderStatus === '下单'">
    <el-form-item label="设计师:" prop="executor">
      <el-tree-select v-model="form.executor" :data="data" :render-after-expand="false" placeholder="请选择设计师" />
    </el-form-item>
    </div>
     <div v-else-if="form.orderStatus === '分单'">
       <el-form-item label="供应商:" prop="orderManager" >
           <el-checkbox v-model="item.checked" :label="item.empName" border v-for="(item,index) in allSupplier" :key="item" style="margin-top: 1%" :disabled="count>0"/>
       </el-form-item>
       <el-form-item label="确认供应商" prop="orderManager" v-show="count==0">
         <el-button type="primary" @click="getChecked" style="margin-top: 2%;margin:0 auto;">确认供应商</el-button>
       </el-form-item>
       <el-form-item label="供应商备注:" prop="orderManager" v-show="checkedSupplier.length>0&&count>0" >

       </el-form-item>
       <el-form-item :label="supplier.empName" v-for="(supplier,index) in checkedSupplier" style="margin-top: 2%">
         <el-input v-model="supplier.comment" type="textarea"  :placeholder="supplier.empName" style="width: 400px" />
       </el-form-item>
     </div>
     <div v-else>
    <el-form-item label="执行人:" prop="executor">
      <el-tree-select v-model="form.executor" :data="data" :render-after-expand="false" placeholder="请选择设计主管" />
    </el-form-item>
    </div>
    <el-form-item label="备注:">
      <el-input v-model="form.comment" type="textarea" style="width: 400px" />
    </el-form-item>
     <el-form-item label="上传图片:" v-if="form.orderStatus != '结束'">
       <el-upload
       v-if="Env=='development'"
         v-model:file-list="fileList"
         :action="'http://localhost:3100/js/a/product/file/upload?orderId='+props.orderid+'&orderStatus='+status_id"
         list-type="picture-card"
         :on-success="uploadSuccess"
         :on-preview="handlePictureCardPreview"
         :on-remove="handleRemove"
       >
         <el-icon><Plus /></el-icon>
       </el-upload>
       <el-upload
       v-else
         v-model:file-list="fileList"
         :action="'http://'+GlobUrl+'/js/a/product/file/upload?orderId='+props.orderid+'&orderStatus='+status_id"
         list-type="picture-card"
         :on-success="uploadSuccess"
         :on-preview="handlePictureCardPreview"
         :on-remove="handleRemove"
       >
         <el-icon><Plus /></el-icon>
       </el-upload>
       <el-dialog v-model="dialogVisible">
         <img w-full :src="dialogImageUrl" alt="Preview Image" />
       </el-dialog>
     </el-form-item>
  </el-form>
<!--  必须有下一状态时，才能进行确认操作-->
  <div class="_button" v-show="showNextStatus">
    <el-button type="primary" size="large" @click="onSubmit(ruleFormRef)" v-if="form.orderStatus != '分单'">确认</el-button>
    <el-button type="primary" size="large" @click="sendData(ruleFormRef)" v-if="form.orderStatus === '分单'">确认</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, watch,defineEmits } from 'vue'
import { OrderListData } from '/@/api/tb/tbOrder'
import { tbAddNext } from '/@/api/tb/tbaddNext'
import { tbDictList } from '/@/api/tb/tbDictType'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import {GetWhole} from "../Util_Function/getOrderWhole"
import {tbFindAllSupplier} from "/@/api/tb/tbSupplierOrder"
import {getEnv } from '/@/utils/env';
import {GlobUrl} from "../Util_Function/uploadPicture"
const Env=getEnv()
const orderstatus = ref([])
const props = defineProps({
  orderid: String
})
let status_id=reactive('')
const emit = defineEmits(['editForm'])
const ruleFormRef=ref<any>()
const form = reactive({
  orderId: '', // 订单号
  executor:'',//客户经理
  orderStatus: '', // 订单状态
  nextorderStatus:'',//下一步订单状态
  reserveAmount: '', // 定金金额
  comment: '' ,// 备注
  estimatedAmount:'',//预估金额
  fileList:'',
})
const fileList =ref<UploadUserFile[]>()
const showNextStatus=ref(true)
const data=ref([])
const loading=ref(true)
watch(
  () => props.orderid, //这样才可以检测到对象里面的值
  async () => {
      loading.value=true
  fileList.value=[]
    const res = await OrderListData({ orderId: props.orderid })
    if (res.list) {
      // console.log(res.list);
      status_id=res.list[0]?.orderStatus
      for (let key in form) {
        form[key] = ''
        form[key] = res.list[0][key]
      }
    }
    getOffices()
  },
  { immediate: true }
)
const getOffices = async () => {
  const status = await tbDictList({ dict: 'the_order_status' })
  orderstatus.value = status.data
  for (let index = 0; index < status.data.length; index++) {
    if(form.orderStatus==status.data[index].dictLabel){
      if (index===status.data.length-1) {
        showNextStatus.value=false
      }else{
        showNextStatus.value=true
        form.nextorderStatus=parseInt(status.data[index+1].dictValue)+''
      }
    }
  }
  form.orderId=props.orderid
  data.value = await GetWhole();
  if(data.value.length&&orderstatus.value.length){
    loading.value=false
  }
}
const rules = reactive({
  orderStatus: [{ required: true,message: '请选择订单状态',trigger: 'change'}],
  nextorderStatus: [{ required: true,message: '请选择订单状态',trigger: 'change'}],
  reserveAmount: [{ required: true,message: '请输入定金金额',trigger: 'blur'}],
  executor: [{ required: true,message: '执行人为必填项',trigger: 'change'}],
  estimatedAmount: [{ required: true,message: '请输入预估金额',trigger: 'blur'}],
})
const onSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate( async(valid) => {
    if (valid) {
      const res = await tbAddNext(form)
  if(res.result){
 
    for (let key in form) {
        form[key]=''
  }
    emit('editForm') 
    ElMessage({
    message:res.message,
    type: 'success',
  })
  }else{
    ElMessage.error(res.message)
  }} 
  })
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
let  url=reactive('')
const pushFile=()=>{
  url=''
  for(let i=0; i<JSON.parse(JSON.stringify(fileList))._value.length;i++){
  if(i==JSON.parse(JSON.stringify(fileList))._value.length-1){
    url=url+JSON.parse(JSON.stringify(fileList))._value[i].response.data.url
  }else{
    url=url+JSON.parse(JSON.stringify(fileList))._value[i].response.data.url+','
  }
  }
  form.fileList=url
  console.log(form.fileList);
  
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  pushFile()
}
//获取到所有的供应商
let allSupplier = ref([
  {empCode:"test",empName:"获取数据",checked:true,comment:""}
])
//选择的供应商
let checkedSupplier = ref([
])
const findAllSupplier = async ()=>{
  const res =  await tbFindAllSupplier()
  allSupplier = res.data
}
findAllSupplier()
let count = ref(0)
const  getChecked = ()=>{
  if (count.value === 0){
    //构建已经选择的内容
    for (let i = 0; i < allSupplier.length; i++) {
      if (allSupplier[i].checked){
        checkedSupplier.value.push(allSupplier[i])
      }
    }
    count.value++;
  }else {
    //已经确认过
    for (let i = 0; i < allSupplier.length; i++) {
      if (allSupplier[i].checked){
        if (!checkedSupplier.value.indexOf(allSupplier[i])){
          checkedSupplier.value.push(allSupplier[i])
        }
      }
    }
    ElMessage.warning("已经确认过了")
  }

}

const sendData =async (formEl)=>{
  //构造相关参数

  let empCodes = [];
  let comments = []
  for (let i = 0; i < checkedSupplier.value.length; i++) {
    empCodes.push(checkedSupplier.value[i].empCode)
    comments.push(checkedSupplier.value[i].comment)
  }
  form.comments = comments.toString()
  form.empCodes = empCodes.toString()
  // 发送请求
  await onSubmit(formEl)

}
const uploadSuccess = (res,file,files)=>{
  if (res.code!=200){
    ElMessage.error("上传失败")
  } else{
    pushFile()
  }
}


const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

</script>

<style lang="less" scoped>
._button {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 50px;
}
</style>
